package com.itheima.framework.factory;

import com.itheima.controller.AccountController;
import com.itheima.framework.util.ParseAnnotation;
import com.itheima.framework.util.XmlBean;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * @program: Implementing springmvc
 * @description:
 * @author: zhanghz001
 * @create: 2020-12-05 10:38
 **/
public class XmlBeanFactory implements BeanFactory {
    private static Map<String, Object> beans;
    private static Map<String, Method> methods;
    private static Map<String, String> urlIdMap;

    public XmlBeanFactory() {
        initBeans();

    }

    public XmlBeanFactory(String path) {
        try {
            XmlBean.load(path);
            initBeans();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }

    }

    private void initBeans() {
        try {
            beans = XmlBean.initBeans();
            //构建methods中uri和beans中id的映射关系
            //methods
            //1.解析所有的类上@RequestMapping注解
            //2.将注解中的值(uri)和方法存储起来，存入到Map<String,Method>

            methods = ParseAnnotation.parseRequestMapping();
            //beans
            urlIdMap = ParseAnnotation.parseUrlMappingInstance(methods, beans);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }

    @Override
    public Object getBean(String beanId) {
        return beans.get(beanId);
    }

    @Override
    public Object getUrlBean(String uri) {
        String beanId = urlIdMap.get(uri);
        if (StringUtils.isNotBlank(beanId)) {
            return beans.get(beanId);
        }
        return null;
    }

    @Override
    public Method getMethod(String uri) {
        return methods.get(uri);
    }

    public static void main(String[] args) {
        BeanFactory beanFactory = new XmlBeanFactory("spring.xml");
        AccountController accountController1 = (AccountController) beanFactory.getBean("accountController");
        AccountController accountController2 = (AccountController) beanFactory.getBean("accountController");
        System.out.println(accountController1);
        System.out.println(accountController1 == accountController2);
    }
}
